<?php
namespace app\shoes\controller;
/** 控制器类引入区 **/
/** 模型类引入区 **/

use app\common\model\HandCard as HandCardM;
use app\common\service\OrdinaryService;
use app\common\service\ReceiverService;
use think\Db;
/**
 * 前台首页控制器
 * @package app\api\controller
 */
class Index extends Auth
{
    public $noNeedLogin = [];

    /**
     * 手牌首页
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $return = HandCardM::getList($getData,$this->userInfo);
            if($return['code'] != 200){
                $this->result($return['msg'], '', 204);
            }
            $this->result('查询成功', $return['data'], 200);
        } else {
            $this->result('请使用post请求', '', 204);
        }
    }


    /**
     * 备注
     */
    public function remarks(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['content']) || empty($getData['content'])){
                $this->result('请填写备注信息', '', 204);
            }
            if(!isset($getData['hand_grant_id']) || empty($getData['hand_grant_id'])){
                $this->result('缺少参数', '', 204);
            }
            $update = Db::name('qt_hand_grant')->where('id',$getData['hand_grant_id'])->update(['content'=>$getData['content']]);
            if($update !== false ){
                $this->result('备注成功', '', 200);
            }
            $this->result('备注失败', '', 204);
        }
        $this->result('无效的请求方式', '', 204);
    }


    /**
     * 取消备注
     */
    public function del_remarks(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['hand_grant_id']) || empty($getData['hand_grant_id'])){
                $this->result('缺少参数', '', 204);
            }
            $update = Db::name('qt_hand_grant')->where('id',$getData['hand_grant_id'])->update(['content'=>'']);
            if($update !== false ){
                $this->result('取消成功', '', 200);
            }
            $this->result('取消失败', '', 204);
        }
        $this->result('无效的请求方式', '', 204);
    }



    /**
     * 取消手牌
     */
    public function cancel(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['hand_grant_id']) || empty($getData['hand_grant_id'])){
                $this->result('缺少参数', '', 204);
            }
            $handGrant = Db::name('qt_hand_grant')->where('id',$getData['hand_grant_id'])->find();
            //添加门票
            $ticket = new \app\common\model\AdmissionTicket();
            $result = $ticket::delAdmissionPrice($handGrant['hand_card_id']);
            if($result['status'] == false){
                $this->result($result['msg'], '', 204);
            }
            //判断是否有未结账的商品和项目
            $projectOrder = Db::name('qt_order_project')
                ->where(['hand_card_id'=>$handGrant['hand_card_id'],'pay_status'=>'0','is_delete'=>'2','is_change'=>'1'])
                ->find();

            $goodsOrder = Db::name('qt_product_order_item')
                ->where(['hand_card_id'=>$handGrant['hand_card_id'],'pay_status'=>'0','status'=>'1'])
                ->find();
            if(!empty($projectOrder) || !empty($goodsOrder)){
                $this->result('手牌未结账', '', 204);
            }
            $handGrant = Db::name('qt_hand_grant')->where('id',$getData['hand_grant_id'])->find();
            $update = Db::name('qt_hand_grant')->where('id',$getData['hand_grant_id'])->update(['status'=>'3']);
            Db::name('qt_hand_card')->where('id',$handGrant['hand_card_id'])->update(['status'=>'1']);
            if($update !== false ){
                $this->result('取消成功', '', 200);
            }
            $this->result('取消失败', '', 204);
        }
        $this->result('无效的请求方式', '', 204);
    }



    /**
     * 发放手牌
     */
    public function grant(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['name']) || empty($getData['name'])){
                $this->result('缺少参数', '', 204);
            }
            if($this->storeInfo['type'] == '1'){
                $this->result('门店模式不正确', '', 204);
            }
            $handCardNames = explode(',',$getData['name']);
            foreach ($handCardNames as $key=>$value){
                $handCard = Db::name('qt_hand_card')->where('name',$value)->find();
                if(empty($handCard)){
                    $this->result('无效的手牌', '', 204);
                }
                if($handCard['status'] != '1'){
                    $this->result('手牌状态有问题', '', 204);
                }
                if($getData['marge'] == '1'){
                    $handCardIds = Db::name('qt_hand_card')->whereIn('name',$handCardNames)->column('id');
                }
                $money = \app\common\model\HandCard::checkMoney($handCard['id']);
                $insert = [
                    'hand_card_id'=>$handCard['id'],
                    'grant_id'=>$this->userInfo['id'],
                    'store_id'=>$this->userInfo['store_id'],
                    'status'=>'2',
                    'money'=>$money,
                    'create_time'=>time()
                ];
                try{
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_hand_card')->where(['id'=>$handCard['id']])->update(['status'=>'2']);
                    $grantID = Db::name('qt_hand_grant')->insertGetId($insert);
                    if($getData['marge'] == '1'){
                        Db::name('qt_hand_grant')->where('id',$grantID)->update(['marge'=>$handCardIds]);
                        //插入记录
                        $log = [
                            'hand_card_id'=>$handCard['id'],
                            'hand_card_name'=>$value,
                            'hand_grant_id'=>$grantID,
                            'store_id'=>$this->userInfo['store_id'],
                            'user_id'=>$this->userInfo['id'],
                            'create_time'=>time(),
                        ];
                        Db::name('qt_hand_card_marge')->insert($log);
                    }
                    //添加门票
                    $ticket = new \app\common\model\AdmissionTicket();
                    $result= $ticket::admissionTicketPrice($handCard['type'],$handCard['id'],$this->userInfo);
                    if($result['status'] == false){
                        $this->result($result['msg'],'',204);
                    }
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    $this->result('发放失败','',204);
                }
            }

            $this->result('发放成功', '', 200);
        }
        $this->result('无效的请求方式', '', 204);
    }


    /**
     * 回收手牌
     */
    public function recovery(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['name']) || empty($getData['name'])){
                $this->result('缺少参数', '', 204);
            }
            if($this->storeInfo['type'] == '1'){
                $this->result('门店模式不正确', '', 204);
            }
            $handCard = Db::name('qt_hand_card')->where('name',$getData['name'])->find();
            if(empty($handCard)){
                $this->result('无效的手牌', '', 204);
            }
            if($handCard['status']  == '3'){
                $this->result('手牌状态有问题', '', 204);
            }
            $update = [
                'status'=>'3',
                'update_time'=>time(),
                'recovery_id'=>$this->userInfo['id']
            ];
            try{
                Db::startTrans();
                //修改订单状态
                Db::name('qt_hand_card')->where(['id'=>$handCard['id']])->update(['status'=>'1']);
                Db::name('qt_hand_grant')->where(['hand_card_id'=>$handCard['id']])->update($update);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('取消失败','',204);
            }
            $this->result('取消成功', '', 200);
        }
        $this->result('无效的请求方式', '', 204);
    }


    /**
     * 更换项目
     */
    public  function  change_project(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            //老项目订单
            $orderProject = Db::name('qt_order_project')->where('is_delete',2)->where('id',$getData['order_project_id'])->find();
            if($orderProject['project_id'] == $getData['project_id']){
                $this->result('所换项目与原来一致，请重新选择', '', 204);
            }
            //新项目
            $newProject = Db::name('qt_project')->where('id',$getData['project_id'])->find();
            $oldProject = Db::name('qt_project')->where('id',$orderProject['project_id'])->find();
            if(!empty($orderProject['start_time'])){
                $startTime = $orderProject['start_time'];
                if($newProject['time'] > $oldProject['time']){
                    $ceil = $newProject['time'] - $oldProject['time'];
                    $endTime = $orderProject['end_time'] + ($ceil*60) ;
                }else{
                    $ceil =$oldProject['time'] -  $newProject['time'];
                    $endTime = $orderProject['end_time'] - ($ceil*60) ;
                }
            }else{
                $startTime = null;
                $endTime = null;
            }
            //新订单信息
            $newOrderProjectInsert = [
                'store_id'=>$orderProject['store_id'],
                'name'=>$newProject['name'],
                'old_name'=>$oldProject['name'],
                'created_order_id'=>$orderProject['created_order_id'],
                'order_id'=>$orderProject['order_id'],
                'engineer_id'=>$getData['engineer_id'],
                'project_id'=>$getData['project_id'],
                'room_id'=>$orderProject['room_id'],
                'hand_card_id'=>$orderProject['hand_card_id'],
                'order_type'=>'1',
                'num'=>$orderProject['num'],
                'price'=>$newProject['price'],
                'status'=>$orderProject['status'],
                'is_add'=>'1',
                'is_change'=>'1',
                'created_time'=>time(),
                'sale_id'=>$this->userInfo['id'],
                'start_time'=>$startTime,
                'end_time'=>$endTime,
            ];
            //插入新项目
            $newProjectId =  Db::name('qt_order_project')->insertGetId($newOrderProjectInsert);
            //更新老项目数据
            Db::name('qt_order_project')->where(['id'=>$getData['order_project_id']])->update(['status'=>'5','is_change'=>'3']);
            if($startTime == null){
                $workStatus = '5';
                $queueStatus = '2';
            }else{
                $workStatus = '4';
                $queueStatus = '3';
            }
            Db::name('qt_order_queue')
                ->where(['user_id'=>$getData['engineer_id']])
                ->update([
                    'old_name'=>$orderProject['name'],
                    'start_time'=>$startTime,
                    'status'=>$queueStatus,
                    'end_time'=>$endTime,
                    'room_id'=>$orderProject['room_id'],
                    'order_project_id'=>$newProjectId
                ]);
            Db::name('qt_users')->where(['id'=>$orderProject['engineer_id']])->update(['work_status'=>$workStatus]);
            //判断接待提成规则
            //1=按下单人项目不管技师做什么项目，2=按技师上钟项目不管下单人下什么项目，3=下单人下单项目和技师上钟项目必须相同才有提成
            if($this->storeInfo['receiver_order_commission_type'] == '2'){
                //删除之前的提成并插入新的接待提成和技师提成
                Db::startTrans();

                try{
                    //删除订单提成
                    Db::name('qt_commission_log')->where(['type'=>'1','order_project_id'=>$orderProject['id']])->delete();
                    //插入新的提成
                    $project = Db::name('qt_project')->where('id',$getData['project_id'])->find();
                    //普通提成
                    $commission = new OrdinaryService();
                    $commission = $commission->showCommission('1','1',$project);
                    //计算接待提成
                    $receiver = new ReceiverService();
                    $receiver = $receiver->showCommission('1', '1', $project);
                    if($this->storeInfo['floor_commission_type'] == '1'){
                        $cashierId =  $orderProject['created_order_id'];
                    }else{
                        $cashierId =  $orderProject['created_order_id'];
                    }
                    $insert = [
                        'store_id' => $this->storeInfo['id'],
                        'cashier_id' => $cashierId,//接待人
                        'user_id' => $getData['engineer_id'],//技师
                        'room_id' => $orderProject['room_id'],
                        'money' => $newProject['price'],
                        'commission' => $commission,//技师提成
                        'receiver' => $receiver,//接待提成
                        'product_id' => $orderProject['project_id'],
                        'type' => '1',
                        'created_time' => time(),
                        'is_pay' => '1',
                        'order_project_id' => $newProjectId,
                        'status' => $orderProject['order_type'],
                        'is_add' => $orderProject['order_type'],
                    ];
                    Db::name('qt_commission_log')->insert($insert);
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    $this->result('操作失败'.$exception->getFile().$exception->getLine().$exception->getMessage(),'',204);
                }
            }
            $this->result('操作成功', '', 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }


}
